package com.cowmooed.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger配置类
 * 用于配置API文档生成相关内容
 */
@Configuration
@EnableSwagger2
public class SwaggerConfiguration implements WebMvcConfigurer {

    /**
     * 创建Swagger Docket对象
     * 配置扫描controller包及其子包
     */
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true) // 启用Swagger
                .select()
                // 扫描controller包及其子包
                .apis(RequestHandlerSelectors.basePackage("com.cowmooed.controller"))
                // 所有路径都需要生成API文档
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 创建API信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("BackCode API文档")
                .description("BackCode项目接口文档，包含所有可用的API接口")
                .version("2.0")
                .contact(new Contact("BackCode团队", "", ""))
                .build();
    }
    
    /**
     * 添加静态资源映射，解决Swagger资源无法访问的问题
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .resourceChain(false);
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/swagger-resources/**")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}